package com.gitee.security.validate;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class CaptchaController {

    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";

    /**
     * 获取验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        Captcha captcha = new Captcha(lineCaptcha.getCode(), 60);
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY, captcha);
        ImageIO.write(lineCaptcha.getImage(), "JPEG", response.getOutputStream());
    }

}
